/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webidewar.jsf;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.model.SelectItem;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.*;

//import webidewar.controller.ResourcesFacade;
import org.WebIDE.ejb.sessions.exceptions.*;
import webidewar.jsf.util.JsfUtil;
//import webidewar.controller.exceptions.NonexistentEntityException;
//import webidewar.controller.exceptions.IllegalOrphanException;
import webidewar.jsf.util.PagingInfo;

/**
 *
 * @author huy
 */
public class ResourcesController {

    private ResourcesFacadeRemote resourcesFacade;

    public ResourcesFacadeRemote getResourcesFacade() {
        return resourcesFacade;
    }

    @EJB
    public void setResourcesFacade(ResourcesFacadeRemote resourcesFacade) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        facesContext.getApplication().getELResolver().setValue(facesContext.getELContext(), null, "resourcesJpa", resourcesFacade);

        this.resourcesFacade = resourcesFacade;
    }

    public ResourcesController() {
        pagingInfo = new PagingInfo();
        converter = new ResourcesConverter();
    }
    private Resources resources = null;
    private List<Resources> resourcesItems = null;
    //private ResourcesFacade resourcesFacade = null;
    private ResourcesConverter converter = null;
    private PagingInfo pagingInfo = null;

    public PagingInfo getPagingInfo() {
        if (pagingInfo.getItemCount() == -1) {
            pagingInfo.setItemCount(resourcesFacade.getResourcesCount());
        }
        return pagingInfo;
    }

    public SelectItem[] getResourcesItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(resourcesFacade.findResourcesEntities(), false);
    }

    public SelectItem[] getResourcesItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(resourcesFacade.findResourcesEntities(), true);
    }

    public Resources getResources() {
        if (resources == null) {
            resources = (Resources) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentResources", converter, null);
        }
        if (resources == null) {
            resources = new Resources();
        }
        return resources;
    }

    public String listSetup() {
        reset(true);
        return "resources_list";
    }

    public String createSetup() {
        reset(false);
        resources = new Resources();
        return "resources_create";
    }

    public String create() {
        try {
            resourcesFacade.create(resources);
            JsfUtil.addSuccessMessage("Resources was successfully created.");
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return listSetup();
    }

    public String detailSetup() {
        return scalarSetup("resources_detail");
    }

    public String editSetup() {
        return scalarSetup("resources_edit");
    }

    private String scalarSetup(String destination) {
        reset(false);
        resources = (Resources) JsfUtil.getObjectFromRequestParameter("jsfcrud.currentResources", converter, null);
        if (resources == null) {
            String requestResourcesString = JsfUtil.getRequestParameter("jsfcrud.currentResources");
            JsfUtil.addErrorMessage("The resources with id " + requestResourcesString + " no longer exists.");
            return relatedOrListOutcome();
        }
        return destination;
    }

    public String edit() {
        String resourcesString = converter.getAsString(FacesContext.getCurrentInstance(), null, resources);
        String currentResourcesString = JsfUtil.getRequestParameter("jsfcrud.currentResources");
        if (resourcesString == null || resourcesString.length() == 0 || !resourcesString.equals(currentResourcesString)) {
            String outcome = editSetup();
            if ("resources_edit".equals(outcome)) {
                JsfUtil.addErrorMessage("Could not edit resources. Try again.");
            }
            return outcome;
        }
        try {
            resourcesFacade.edit(resources);
            JsfUtil.addSuccessMessage("Resources was successfully updated.");
        } catch (IllegalOrphanException oe) {
            JsfUtil.addErrorMessages(oe.getMessages());
            return null;
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return listSetup();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return detailSetup();
    }

    public String destroy() {
        String idAsString = JsfUtil.getRequestParameter("jsfcrud.currentResources");
        Integer id = new Integer(idAsString);
        try {
            resourcesFacade.destroy(id);
            JsfUtil.addSuccessMessage("Resources was successfully deleted.");
        } catch (IllegalOrphanException oe) {
            JsfUtil.addErrorMessages(oe.getMessages());
            return null;
        } catch (NonexistentEntityException ne) {
            JsfUtil.addErrorMessage(ne.getLocalizedMessage());
            return relatedOrListOutcome();
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "A persistence error occurred.");
            return null;
        }
        return relatedOrListOutcome();
    }

    private String relatedOrListOutcome() {
        String relatedControllerOutcome = relatedControllerOutcome();
        if (relatedControllerOutcome != null) {
            return relatedControllerOutcome;
        }
        return listSetup();
    }

    public List<Resources> getResourcesItems() {
        if (resourcesItems == null) {
            getPagingInfo();
            resourcesItems = resourcesFacade.findResourcesEntities(pagingInfo.getBatchSize(), pagingInfo.getFirstItem());
        }
        return resourcesItems;
    }

    public String next() {
        reset(false);
        getPagingInfo().nextPage();
        return "resources_list";
    }

    public String prev() {
        reset(false);
        getPagingInfo().previousPage();
        return "resources_list";
    }

    private String relatedControllerOutcome() {
        String relatedControllerString = JsfUtil.getRequestParameter("jsfcrud.relatedController");
        String relatedControllerTypeString = JsfUtil.getRequestParameter("jsfcrud.relatedControllerType");
        if (relatedControllerString != null && relatedControllerTypeString != null) {
            FacesContext context = FacesContext.getCurrentInstance();
            Object relatedController = context.getApplication().getELResolver().getValue(context.getELContext(), null, relatedControllerString);
            try {
                Class<?> relatedControllerType = Class.forName(relatedControllerTypeString);
                Method detailSetupMethod = relatedControllerType.getMethod("detailSetup");
                return (String) detailSetupMethod.invoke(relatedController);
            } catch (ClassNotFoundException e) {
                throw new FacesException(e);
            } catch (NoSuchMethodException e) {
                throw new FacesException(e);
            } catch (IllegalAccessException e) {
                throw new FacesException(e);
            } catch (InvocationTargetException e) {
                throw new FacesException(e);
            }
        }
        return null;
    }

    private void reset(boolean resetFirstItem) {
        resources = null;
        resourcesItems = null;
        pagingInfo.setItemCount(-1);
        if (resetFirstItem) {
            pagingInfo.setFirstItem(0);
        }
    }

    public void validateCreate(FacesContext facesContext, UIComponent component, Object value) {
        Resources newResources = new Resources();
        String newResourcesString = converter.getAsString(FacesContext.getCurrentInstance(), null, newResources);
        String resourcesString = converter.getAsString(FacesContext.getCurrentInstance(), null, resources);
        if (!newResourcesString.equals(resourcesString)) {
            createSetup();
        }
    }

    public Converter getConverter() {
        return converter;
    }
}
